package com.dqy.twserver.server.codec;

import com.dqy.twserver.server.dto.GameDto;
import com.google.gson.GsonBuilder;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//编码器
public class DataEncode extends MessageToByteEncoder<GameDto> {
    static GsonBuilder gsonBuilder=new GsonBuilder();
    static Logger logger = LoggerFactory.getLogger(DataEncode.class);
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, GameDto gameDto, ByteBuf byteBuf) throws Exception {
        try {

            logger.info("[DataEncode]开始编码...");
            String json = gsonBuilder.create().toJson(gameDto);
            byte[] bytes = json.getBytes();

            byteBuf.writeInt(Integer.reverseBytes(bytes.length));
            byteBuf.writeBytes(bytes);

            logger.info("[DataEncode]编码完毕...长度{}",bytes.length);
        }catch (Exception e){
            GameDto resp=new GameDto();
            resp.setSts(500);
            resp.setInfo("服务端编码器异常");
            String json = gsonBuilder.create().toJson(resp);
            byte[] bytes = json.getBytes();

            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
            logger.info("编码失败,{}",e);
        }

    }
}
